package com.medsoft.drpcp.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.medsoft.drpcp.meta.DrpcpMetaConstant;

public class DrpcpServerBusiHandler extends SimpleChannelInboundHandler<Object> {
	static final Logger logger = LoggerFactory.getLogger(DrpcpServerBusiHandler.class);
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		logger.debug("drpcp server received request: " + msg);
		if(msg.toString().equals(DrpcpMetaConstant.HEARTBEAT_MSG)) {
			ctx.channel().writeAndFlush(msg);
		} else {
			String retJson = RpcServiceDispatcher.execute(msg.toString());
			logger.debug("drpcp server process finished,return: " + retJson);
	        ctx.channel().writeAndFlush(retJson);
		}
	}

	@Override  
    public void exceptionCaught(ChannelHandlerContext ctx,  
            Throwable cause) throws Exception {  
        logger.error("Unexpected exception from downstream.");
        cause.printStackTrace();
        ctx.close();  
    }
}
